package zero.tech.games.logic.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;

import zero.tech.core.util.RandomUtil;
import zero.tech.games.common.GameConfig;
import zero.tech.games.common.RoomNodeUtil;
import zero.tech.games.common.ThreadRunner;
import zero.tech.games.common.data.AIRoomNodeConfig;
import zero.tech.games.common.data.RoomNode;
import zero.tech.games.entity.games.Club;
import zero.tech.games.logic.util.LogicUtil;
@Configuration
public class AIRoomNodeRunner extends ThreadRunner{
	@Value("${server.address}")
	private String host;
	@Value("${server.port}")
	private String port;
	@Value("${spring.application.name}")
	private String service_id;
	@Autowired
	private RoomNodeUtil roomNodeUtil;
	@Override
	public void process() {
		initRobot();
		while(true) {
			int rand=RandomUtil.randInt(5000, 30000);
			try {
				Thread.sleep(10000+rand);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			try {
				handle();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void initRobot() {
		
	}

	private void handle() {
		List<RoomNode> list=roomNodeUtil.getAllRooms();
		Map<String,Integer> ai_roomnode_count_map=getAiRoomNodeCount(list);
		Map<String,AIRoomNodeConfig> map=ServerData.ai_roomnode_map;
		for(Entry<String,AIRoomNodeConfig> entry:map.entrySet()) {
			AIRoomNodeConfig aiRoomNodeConfig = entry.getValue();
			int cur_count=ai_roomnode_count_map.get(entry.getKey())==null?0:ai_roomnode_count_map.get(entry.getKey());
			int max=aiRoomNodeConfig.getMax();
			int min=aiRoomNodeConfig.getMin();
			int area=RandomUtil.randInt(0, 10);
			int add_or_reduce=RandomUtil.randInt(100);
			if(cur_count<min) {
				if(add_or_reduce<=80) {
					addRoomNodes(aiRoomNodeConfig,area);
				}else {
					reduceRoomNodes(list,aiRoomNodeConfig,area);
				}
			}else if(cur_count>max) {
				if(add_or_reduce<=20) {
					addRoomNodes(aiRoomNodeConfig,area);
				}else {
					reduceRoomNodes(list,aiRoomNodeConfig,area);
				}
			}else {
				if(add_or_reduce<=55) {
					addRoomNodes(aiRoomNodeConfig,area);
				}else {
					reduceRoomNodes(list,aiRoomNodeConfig,area);
				}
			}
		}
	}

	private void reduceRoomNodes(List<RoomNode> list, AIRoomNodeConfig aiRoomNodeConfig, int area) {
		int count=0;
		List<RoomNode> roomNodes=new ArrayList<>();
		Club club=JSONObject.parseObject(aiRoomNodeConfig.getClubStr(),Club.class);
		GameConfig gameConfig=JSONObject.parseObject(aiRoomNodeConfig.getConfigStr(),GameConfig.class);
		for(RoomNode roomNode:list) {
			if(roomNode.getClub_id().equals(String.valueOf(club.getClub_id()))
					&&roomNode.getPipei_key().equals(gameConfig.getPipei_key())
					&&roomNode.getAi()==1) {
				roomNodes.add(roomNode);
				count++;
			}
			if(count>area) {
				break;
			}
		}
		if(!roomNodes.isEmpty()) {
			RoomNode[] nodes=new RoomNode[roomNodes.size()];
			roomNodes.toArray(nodes);
			roomNodeUtil.deleteBatch(nodes);
			System.out.println("删除机器人房间节点");
		}
	}

	private void addRoomNodes(AIRoomNodeConfig aiRoomNodeConfig, int area) {
		List<RoomNode> list=new ArrayList<>();
		String config_str=aiRoomNodeConfig.getConfigStr();
		GameConfig gameConfig=JSONObject.parseObject(config_str,GameConfig.class);
		Club club=JSONObject.parseObject(aiRoomNodeConfig.getClubStr(),Club.class);
		for(int i=0;i<area;i++) {
			RoomNode roomNode=new RoomNode();
			roomNode.setHost(host);
			roomNode.setPort(port);
			roomNode.setService_id(service_id);
			roomNode.setRoom_id(LogicUtil.randRoomId());
			roomNode.setMax_player(gameConfig.getMax_player());
			roomNode.setGame_id(gameConfig.getGame_id());
			roomNode.setConfigStr(config_str);
			roomNode.setName(gameConfig.getName());
			roomNode.setPipei_key(gameConfig.getPipei_key());
			roomNode.setClub_id(String.valueOf(club.getClub_id()));
			roomNode.setAi(1);
			list.add(roomNode);
		}
		RoomNode[] nodes=new RoomNode[list.size()];
		roomNodeUtil.insertOrUpdateBatch(list.toArray(nodes));	
		System.out.println("增加机器人房间节点");
	}

	private Map<String, Integer> getAiRoomNodeCount(List<RoomNode> list) {
		Map<String,Integer> map = new HashMap<String, Integer>();
		for(RoomNode roomNode:list) {
			if(roomNode.getAi()==1) {
				String key=roomNode.getClub_id()+"###"+roomNode.getPipei_key();
				if(!map.containsKey(key)) {
					map.put(key, 1);
				}else {
					int old=map.get(key);
					map.put(key, old+1);
				}
			}
		}
		return map;
	}

}
